<?php

/**
 * pradmin actions.
 *
 * @package    sf_sandbox
 * @subpackage pradmin
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 2288 2006-10-02 15:22:13Z fabien $
 */
class pradminActions extends autopradminActions
{
    
    public function executeGet()
    {
        $file = strip_tags($this->getRequestParameter('file', ''));
        if( $file )
        {
            $filename = sprintf('%s/%s.csv', sfConfig::get('sf_upload_dir'), date('Y-m-d'));
            header("Content-type: application/octet-stream");
            header('Content-Disposition: attachment; filename="' . $file . '.csv"');
            readfile($filename);
        }
        exit();
    }
    
    public function executeSync()
    {
        /* @var $pr Product */
        
        $status = MyConstants::STATUS_FAILED;
        
        $code = strip_tags($this->getRequestParameter('code', ''));
        $price = $this->getRequestParameter('price', '0');
        $qnt = (int)$this->getRequestParameter('qnt', 0);
        if( $code )
        {
            $c = new Criteria();
            $c->add(ProductPeer::CODE, $code);
            $pr = ProductPeer::doSelectOne($c);
            if( $pr )
            {
                $pr->setPrice($price);
                $pr->setQuantity($qnt);
                $pr->save();
                
                $status = MyConstants::STATUS_APPROVED;
            }
        }

        $this->setLayout(false);
        return $this->renderText($status);
    }
    
    public function executeQuantityexport()
    {
        if( $this->getRequest()->getMethod() == sfRequest::POST )
        {
            sfLoader::loadHelpers('Partial');
            $status = MyConstants::STATUS_FAILED;
            
            $c = new Criteria();
            $c->add(ProductPeer::STATUS_ID, MyConstants::STATUS_DELETED, Criteria::NOT_EQUAL);
            $c->addAscendingOrderByColumn(ProductPeer::CODE);
            $products = ProductPeer::doSelect($c);
            
            if( $products )
            {
                $filename = sprintf('%s/%s.csv', sfConfig::get('sf_upload_dir'), date('Y-m-d'));
                //debugvar('Saving as: ' . $filename);
                $fp = @fopen($filename, 'w');
                if( $fp )
                {
                    $str = '';
                    foreach( $products as $product )
                    {
                        $str .= get_partial(
                                    'export_csv_row'
                                    , array(
                                        'product' => $product
                                    ));
                    }
                    fwrite($fp, $str);
                    @fclose($fp);
                    $status = MyConstants::STATUS_APPROVED;
                    $this->setFlash('filename', date('Y-m-d'));
                }
            }

            $this->setFlash('status', $status);
            
            return $this->redirect('pradmin/quantityexport');
        }
        
        if( $this->hasFlash('status') )
        {
            $this->status = (int)$this->getFlash('status');
        }else 
        {
            $this->status = 0;
        }
        if( $this->hasFlash('filename') )
        {
            $this->filename = $this->getFlash('filename');
        }else 
        {
            $this->filename = '';
        }
    }
    
    protected function addFiltersCriteria($c)
    {
        if (isset($this->filters['id_is_empty']))
        {
            $criterion = $c->getNewCriterion(ProductPeer::ID, '');
            $criterion->addOr($c->getNewCriterion(ProductPeer::ID, null, Criteria::ISNULL));
            $c->add($criterion);
        }
        else if (isset($this->filters['id']) && $this->filters['id'] !== '')
        {
            $c->add(ProductPeer::ID, $this->filters['id']);
        }
        if (isset($this->filters['code_is_empty']))
        {
            $criterion = $c->getNewCriterion(ProductPeer::CODE, '');
            $criterion->addOr($c->getNewCriterion(ProductPeer::CODE, null, Criteria::ISNULL));
            $c->add($criterion);
        }
        else if (isset($this->filters['code']) && $this->filters['code'] !== '')
        {
            $c->add(ProductPeer::CODE, strtr($this->filters['code'], '*', '%'), Criteria::LIKE);
        }
        if (isset($this->filters['status_id_is_empty']))
        {
            $criterion = $c->getNewCriterion(ProductPeer::STATUS_ID, '');
            $criterion->addOr($c->getNewCriterion(ProductPeer::STATUS_ID, null, Criteria::ISNULL));
            $c->add($criterion);
        }
        else if (isset($this->filters['status_id']) && $this->filters['status_id'] !== '')
        {
            $c->add(ProductPeer::STATUS_ID, $this->filters['status_id']);
        }
        if( isset($this->filters['tag_id']) && ($this->filters['tag_id'] > 0) )
        {
            /*	    	$arTags = $this->filters['tag_id'];
             if( !empty($arTags) )
             {*/
             
            $c->add(ProductPeer::TAGS, ProductPeer::TAGS . ' REGEXP "[[:<:]]' . $this->filters['tag_id'] . '[[:>:]]"', Criteria::CUSTOM);
            /*}
             }*/
        }
    }

	
	
    protected function updateProductFromRequest()
    {
        parent::updateProductFromRequest();
        $product = $this->getRequestParameter('product');

//        if (isset($product['producer']))
//        {
//            $producers = implode(':', $product['producer']);
//            //debugvar($producers);
//            //exit('exitttttting...');
//            $this->product->setProducer($producers);
//        }
        if( $this->hasRequestParameter('product[category_id]') )
        {
            $this->product->setCategoryId( (int)$this->getRequestParameter('product[category_id]') );
        }
        
        if($this->hasRequestParameter('product[is_new]'))
        {
            $this->product->addTag(Product::NEW_TAG);
        }else 
        {
            $this->product->removeTag(Product::NEW_TAG);
        }
        
        if($this->hasRequestParameter('product[is_promo]'))
        {
            $this->product->addTag(Product::PROMO_TAG);
        }else
        {
            $this->product->removeTag(Product::PROMO_TAG);
        }
        
    }
    protected function saveProduct($product)
    {
//        debugvar($this->getRequest()->getParameterHolder());
        $product->setCulture($this->getUser()->getCulture());
        
        $this->updateProductFromRequest();
        
        $product->setUserId(get_user_id());
        $product->setPrice(str_replace(array(',', '.'), '', $this->getRequestParameter('product[price]')));
        $product->setPricePromo(str_replace(array(',', '.'), '', $this->getRequestParameter('product[price_promo]')));
        
//        debugvar($product);
//        exit('saving...');
        $product->save();
        
        $fileName = $this->getRequest()->getFileName('product[photo]');
        $filePath = $this->getRequest()->getFilePath('product[photo]');

        if( !empty($filePath) )
        {
            Files::saveTo(
            $fileName
            , $filePath
            , $product->getId()
            , get_user_id()
            , MyConstants::TYPE_PRODUCT
            , $this->getUser()->getCulture()
            , $product->getStatusId()
            , $fileName
            , ''
            );
        }
    }

    protected function getProductOrCreate($id = 'id')
    {
        /* @var $product Product */

        $product = parent::getProductOrCreate($id);
        $product->setCulture($this->getUser()->getCulture());
        $product->setStatusId( $product->getStatusId() ? $product->getStatusId() : MyConstants::STATUS_NEW );
        
        if( strlen($product->getCode()) < 1 )
        {
            $product->setCode(Product::generateCode());
        }
//        debugvar($product, 'Filled w/ code:');
//        exit('saving...');
        
        return $product;
    }


    /**
     * Deletes image by uname (uname from request)
     */
    public function executeDeleteimg()
    {
        if( $this->getRequestParameter('uname') )
        {
            $uname = Files::getNameFromUrl($this->getRequestParameter('uname'));
            //$file = Files::getNameFromUrl($this->getRequestParameter('uname'));
            Files::deleteByUname($uname, true);
        }

        $this->redirect('pradmin/edit?id=' . $this->getRequestParameter('id'));
    }
    public function executeDisable()
    {
        $id = (int)$this->getRequestParameter('id', 0);
        //debugvar('Id: ' . $id);
        $obj = ProductPeer::retrieveByPk($id);
        $this->forward404Unless($obj);

        $obj->setStatusId(MyConstants::STATUS_DELETED);
        $obj->save();
        $this->redirect('pradmin/list?id=' . $id);
    }
    public function executeEnable()
    {
        $id = (int)$this->getRequestParameter('id', 0);
        //debugvar('Id: ' . $id);
        $obj = ProductPeer::retrieveByPk($id);
        $this->forward404Unless($obj);

        $obj->setStatusId(MyConstants::STATUS_APPROVED);
        $obj->save();
        $this->redirect('pradmin/list?id=' . $id);
    }
    
    public function handleErrorSave()
    {
        $this->product = $this->getProductOrCreate();
        $this->updateProductFromRequest();
        $this->labels = $this->getLabels();
        
        $this->setTemplate('edit');
        return sfView::SUCCESS;
    }
    
    public function validateSave()
    {
        $isOk = true;
        
        $code = empty($this->product) ? $this->getRequestParameter('product[code]', '') : $this->product->getCode();
        $id = (int)$this->getRequestParameter('id', 0);
        
        // Let's check if such code exists for other products
        if( strlen($code) >= sfConfig::get('app_limits_length_of_code', 8) )
        {
            $c = new Criteria();
            $c->add(ProductPeer::CODE, $code);
            $product = ProductPeer::doSelectOne($c);
            
            if( $product && ($product->getId() != $id) )
            {
                $this->getRequest()->setError('product{code}', 'Error - value is duplicated!');
                $isOk = false;
            }
        }
        
        return $isOk;
    }
}
